import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { useState, useEffect, useRef } from 'react';

import workbenchService from '@/api/services/workbenchService';
import { Search } from '@/components/eai-design';
import NotData from '@/components/NotData';
import { useUserInfo } from '@/store/userStore';

import type { ButtonProps } from 'antd';

interface WorkBasePublicProps {
  activePublicTag?: string;
  publicTagChange?: (data: string) => void;
}

interface TagOption {
  key: string;
  label: string;
  buttonProps?: ButtonProps;
  icon: string;
}

export default function WorkBasePublic({ activePublicTag, publicTagChange }: WorkBasePublicProps) {
  const { role } = useUserInfo();
  const [filterOptions, setFilterOptions] = useState<TagOption[]>([
    { key: 'all', label: '全部', icon: 'work-ic1' },
  ]);
  const [isDropdownVisible, setIsDropdownVisible] = useState(false);
  const [_tagsLoading, setTagsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState<'left' | 'right'>('left');

  const MAX_VISIBLE_TAGS = 8;

  // 获取标签数据
  useEffect(() => {
    const fetchTags = async () => {
      // 只有管理员才获取标签
      if (role?.code === 'super_admin' || role?.code === 'admin') {
        setTagsLoading(true);
        try {
          const res = await workbenchService.getAppTagList();
          const tags = res.tags || [];

          // 将标签数据转换为需要的格式
          const formattedTags = tags.map((tag: { name: string; id: string }, index: number) => ({
            key: tag.id,
            label: tag.name,
            icon: `work-ic${index + 2}`, // 从work-ic2开始，因为work-ic1用于"全部"
          }));

          // 合并默认的"全部"选项和从接口获取的标签
          setFilterOptions([{ key: 'all', label: '全部', icon: 'work-ic1' }, ...formattedTags]);
        } catch (error) {
          console.error('获取标签失败:', error);
          setFilterOptions([{ key: 'all', label: '全部', icon: 'work-ic1' }]);
        } finally {
          setTagsLoading(false);
        }
      }
    };

    fetchTags();
  }, [role]); // 当角色变化时重新获取

  // 处理过滤逻辑
  const handleFilterClick = (type: string) => {
    publicTagChange?.(type);
    setIsDropdownVisible(false); // 选择标签后关闭下拉窗口
  };

  // 显示的标签（前8个）
  const visibleTags = filterOptions.slice(0, MAX_VISIBLE_TAGS);
  // 剩余的标签
  const remainingTags = filterOptions.slice(MAX_VISIBLE_TAGS);
  // 是否需要显示"更多"按钮
  const showMoreButton = filterOptions.length > MAX_VISIBLE_TAGS;

  // 检查当前选中的标签是否在剩余标签中
  const selectedTagInRemaining = remainingTags.find((tag) => tag.label === activePublicTag);
  // "更多"按钮显示的文本
  const moreButtonText = selectedTagInRemaining
    ? `${
        selectedTagInRemaining.label.length > 20
          ? `${selectedTagInRemaining.label.slice(0, 20)}...`
          : selectedTagInRemaining.label
      } `
    : '更多 ';

  // 过滤标签（只显示第9个及以后的标签）
  const remainingOptions = filterOptions.slice(MAX_VISIBLE_TAGS);
  const filteredOptions = remainingOptions.filter((option) =>
    option.label.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  // 点击外部关闭下拉窗口
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownVisible(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 监听窗口大小变化，重新计算弹窗位置
  useEffect(() => {
    const handleResize = () => {
      if (isDropdownVisible && dropdownRef.current) {
        const rect = dropdownRef.current.getBoundingClientRect();
        const windowWidth = window.innerWidth;
        // 根据屏幕大小确定弹窗宽度，与打开时的计算保持一致
        const dropdownWidth = windowWidth < 640 ? Math.min(300, windowWidth * 0.9) : 400;

        if (rect.left + dropdownWidth > windowWidth - 20) {
          setDropdownPosition('right');
        } else {
          setDropdownPosition('left');
        }
      }
    };

    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [isDropdownVisible]);

  return (
    <div className="relative">
      <div className="flex items-center justify-between">
        <div className="flex cursor-pointer items-center justify-start gap-2">
          {visibleTags.map(({ key, label }) => {
            return (
              <div
                key={key}
                className={`  !mr-1 mb-4 flex !h-8 items-center  justify-center rounded-md px-3 text-sm`}
                onClick={() => handleFilterClick(label)}
                style={
                  activePublicTag === label
                    ? {
                        background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)',
                        color: '#fff',
                      }
                    : { background: 'white', color: '#4E5969' }
                }
              >
                <span className="max-w-[120px] truncate" title={label}>
                  {label.length > 20 ? `${label.slice(0, 20)}...` : label}
                </span>
              </div>
            );
          })}
          {showMoreButton && (
            <div className="relative" ref={dropdownRef}>
              <div
                className="!mr-1 mb-4 flex !h-8 cursor-pointer items-center justify-center rounded-md px-3 text-sm"
                onMouseEnter={() => setIsDropdownVisible(true)}
                onMouseLeave={(e) => {
                  if (!dropdownRef.current?.contains(e.relatedTarget as Node)) {
                    setIsDropdownVisible(false);
                  }
                }}
                style={
                  selectedTagInRemaining
                    ? {
                        background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)',
                        color: '#fff',
                      }
                    : { background: 'white', color: '#4E5969' }
                }
              >
                <span>
                  {moreButtonText}
                  {isDropdownVisible ? (
                    <UpOutlined className="ml-1 text-xs" />
                  ) : (
                    <DownOutlined className="ml-1 text-xs" />
                  )}
                </span>
              </div>

              {/* 下拉窗口 */}
              {isDropdownVisible && (
                <div
                  className={`absolute top-full z-50 mt-[-15px] w-[304px]  rounded-lg border border-gray-200 bg-white  shadow-lg sm:w-[304px] sm:p-2 ${
                    dropdownPosition === 'right' ? 'right-0' : 'left-0'
                  }`}
                  style={{
                    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                    minWidth: '280px',
                    maxHeight: '70vh',
                  }}
                >
                  <div className="mb-2">
                    <Search
                      type="text"
                      placeholder="搜索"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                  </div>
                  <div className="flex max-h-48 flex-wrap gap-2 sm:max-h-60">
                    {filteredOptions?.length > 0 ? (
                      filteredOptions.map(({ key, label }) => (
                        <div
                          key={key}
                          className="flex h-8  cursor-pointer items-center justify-center rounded-md px-3 text-sm transition-colors hover:bg-gray-100"
                          onClick={() => handleFilterClick(label)}
                          style={
                            activePublicTag === label
                              ? {
                                  background: 'var(--brand-color-light)',
                                  color: 'var(--brand-color)',
                                }
                              : { background: 'bg-WhiteSmoke', color: 'var(--text-4)' }
                          }
                        >
                          <span title={label}>
                            {label.length > 20 ? `${label.slice(0, 20)}...` : label}
                          </span>
                        </div>
                      ))
                    ) : (
                      <div className="w-full py-4 text-center text-sm text-gray">
                        <NotData />
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
